<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <!-- 书籍搜索框 -->
      <el-form-item label="书籍名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入书籍名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!--刷新按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="medium " :data="postList">
      <el-table-column label="序号" type="index" align="center"/>
      <el-table-column label="书名" width="180" type="name" align="center" prop="name"/>
      <el-table-column label="isbn编号" width="180" type="isbn" align="center" prop="isbn"/>
      <el-table-column label="位置" width="180" align="center" prop="location">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.location!=null">{{ scope.row.location }}</el-tag>
          <el-tag type="danger" v-else>书架位置暂无</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="160" align="center" prop="number">
        <template slot-scope="scope">
          <el-tag type="warning">{{ scope.row.number }}本</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="上架数量" width="180" align="center" prop="shelvedNumber">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.shelvedNumber===0">
            暂未上架
          </el-tag>
          <el-tag type="success" v-else>{{ scope.row.shelvedNumber }}本</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="medium " type="primary" plain icon="el-icon-set-up" @click="dialogUp(scope.row)"
          >上架
          </el-button>
          <el-button :disabled="scope.row.shelvedNumber===0?true:false" @click="dialogDown(scope.row)" size="medium"
                     type="warning" plain icon="el-icon-receiving"
          >下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--   上架 dialog-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%">

      <el-form :rules="rules" ref="form" :model="itemData" label-width="120px">
        <el-form-item label="书籍名称" prop="name">
          <el-input disabled v-model="itemData.name"></el-input>
        </el-form-item>
        <el-form-item label="isbn编号" prop="isbn">
          <el-input disabled v-model="itemData.isbn"></el-input>
        </el-form-item>
        <el-form-item label="书架位置" prop="location">
          <el-input v-model="itemData.location"
                    :placeholder="itemData.location===null?'当前书架位置未填写':''"></el-input>
        </el-form-item>
        <el-form-item label="库存数量（本）" prop="number">
          <el-input disabled v-model="itemData.number+'本'"></el-input>
        </el-form-item>
        <el-form-item label="上架数量（本）" prop="shelvedNumber">
          <el-input
            v-model="itemData.shelvedNumber"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogHandle('form')">确 定</el-button>
  </span>
    </el-dialog>


    <!--  下架dialog  -->

    <el-dialog
      title="提示"
      :visible.sync="dialogDownVisible"
      width="50%">

      <el-form :rules="rulesdown" ref="form" :model="itemData" label-width="120px">
        <el-form-item label="书籍名称" prop="name">
          <el-input disabled v-model="itemData.name"></el-input>
        </el-form-item>
        <el-form-item label="isbn编号" prop="isbn">
          <el-input disabled v-model="itemData.isbn"></el-input>
        </el-form-item>
        <el-form-item label="书架位置" prop="location">
          <el-input disabled v-model="itemData.location"
                    :placeholder="itemData.location===null?'当前书架位置未填写':''"></el-input>
        </el-form-item>
        <el-form-item label="库存数量（本）" prop="number">
          <el-input disabled v-model="itemData.number+'本'"></el-input>
        </el-form-item>
        <el-form-item label="已上架数量（本）">
          <el-input
            disabled
            v-model="this.upNum"></el-input>
        </el-form-item>
        <el-form-item label="下架数量（本）" prop="shelvedNumber">
          <el-input
            v-model="itemData.shelvedNumber"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogDownVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogDownHandle('form')">确 定</el-button>
  </span>
    </el-dialog>


    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 点击详情弹出框 -->
    <el-dialog title="图书详情" width="80%" :visible.sync="isShowInfo" center custom-class="infoDialog">
      <infoTable v-show="isShowInfo" :infoData="infoData"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowInfo = false">取 消</el-button>
        <el-button type="primary" @click="isShowInfo = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加书籍对话框 -->
    <addBookTable v-if="isShowAdd" @closeAddTable="handleCloseAddTable"/>
    <!-- 修改书籍对话框 -->
    <editTable v-if="isShowEdit" @closeEditTable="handleCloseEditTable" :editData="editData"/>
  </div>
</template>

<script>
import {selectshelved, addShelved, downShelved} from '@/api/inventory/index'
import {listPost, getPost, delPost, addPost, updatePost} from "@/api/system/post";
import Pagination from '@/components/Pagination/index'
import {getAllBook, addPublishAndLanguageDict, delBook, getDict, addDict} from '@/api/request.js'
import editTable from '@/components/ManagementTable/editTable.vue'
import infoTable from '@/components/ManagementTable/infoTable.vue'
import addBookTable from '@/components/ManagementTable/addBookTable.vue'
import imageUpload from '@/components/ManagementTable/ImageUpload.vue'

export default {
  name: "Inventory",
  dicts: ['sys_normal_disable'],
  components: {
    infoTable,
    imageUpload,
    addBookTable,
    editTable
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === 0 || value === '') {
        callback(new Error('上架数量不能为0'));
      } else {
        if (parseInt(value) > parseInt(this.itemData.number)) {
          callback(new Error('上架数量超出库存数量'));
          //this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };

    var validatePassDown = (rule, value, callback) => {
      if (parseInt(value) === 0 || value === '') {
        callback(new Error('下架数量不能为0'));
      } else {
        if (parseInt(value) > parseInt(this.upNum)) {
          callback(new Error('下架数量超出限制'));
          //this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    return {
      //test
      testquery: {
        type: 'publish'
      },
      dialogVisible: false,
      //需要修改的图书信息
      editData: {},
      // 是否显示修改图书弹框
      isShowEdit: false,
      //是否显示添加图书弹框
      isShowAdd: false,
      //详情书籍的信息
      infoData: {},
      //详情弹出框
      isShowInfo: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 书籍表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询书籍参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
      },
      //已上架数量
      upNum: 0,
      // 表单参数
      form: {},

      itemData: {},
      dialogDownVisible: false,


      rules: {
        location: [
          {required: true, message: '请输入书架位置', trigger: 'blur'},
        ],
        shelvedNumber: [
          {required: true, message: '请输入需要上架的数量', trigger: 'blur'},
          {
            type: 'number', required: true, validator: validatePass
          }
        ],
      },
      rulesdown: {
        location: [
          {required: true, message: '请输入书架位置', trigger: 'blur'},
        ],
        shelvedNumber: [
          {required: true, message: '请输入需要下架的数量', trigger: 'blur'},
          {
            type: 'number', required: true, validator: validatePassDown
          }
        ],
      },


    };
  },

  created() {
    this.getList();
  },
  methods: {
    dialogUp(item) {
      this.dialogVisible = true
      console.log(item)
      this.itemData = item
    },
    dialogDown(item) {
      this.upNum = item.shelvedNumber
      this.dialogDownVisible = true
      this.itemData = item
      console.log(item)
    },
    onSubmit() {
      console.log(1)
    },

    dialogHandle(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          addShelved({
            'bookId': this.itemData.bookId,
            'shelvedNumber': this.itemData.shelvedNumber,
            'location': this.itemData.location + ''
          }).then(res => {
            if (res.code === 200) {
              this.dialogVisible = false
              this.itemData = {}
              this.$message.success(res.msg)
              this.getList()
            }
          })
        } else {

          return false;
        }
      });

    },

    //下架dialog
    dialogDownHandle(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          downShelved({
            'bookId': this.itemData.bookId,
            'shelvedNumber': this.itemData.shelvedNumber,
            'location': this.itemData.location + ''
          }).then(res => {
            if (res.code === 200 && (res.msg === '上架成功' || res.msg === '下架完成')) {
              this.$message.success(res.msg)
              this.itemData = {}

              this.getList()

            } else {
              //this.itemData.shelvedNumber = 0
              this.$message.warning(res.msg)
            }
            this.dialogDownVisible = false
            this.itemData = {}


          })
        } else {
          return false;
        }
      });
    },
    //根据bookId删除图书
    delBookById() {
      this.loading = true;
      delBook({"bookIds": this.ids}).then(res => {
        this.loading = false;
        console.log("删除接口调用成功,删除的书籍编号", this.ids)
        //删除完书籍后选中ids清空
        this.ids = []
        this.getList()
      })
    },
    //关闭显示添加图书弹框,并刷新数据
    handleCloseAddTable() {
      this.isShowAdd = false
      // 并刷新数据
      this.getList()
    },
    //关闭显示修改图书弹框,并刷新数据
    handleCloseEditTable() {
      this.isShowEdit = false
      // 并刷新数据
      this.getList()
    },
    // // 重置infoData
    restInfoData() {
      this.infoData = {}
    },
    /** 查询书籍列表 */
    getList() {
      this.loading = true;

      selectshelved(this.queryParams).then(res => {
        this.postList = res.rows
        // this.total = 59
        this.total = res.total
        this.loading = false;
      }).catch(err => {
        console.log("查询书籍接口调用失败")
      })
    },


    // 取消按钮
    cancel() {
      this.addTableVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      //this.form = {
      //  postId: undefined,
      //  postCode: undefined,
      //  postName: undefined,
      //  postSort: 0,
      //  status: "0",
      //  remark: undefined
      //};
      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 将刷新时携带的搜索关键字清空，防止查询关键字
      this.queryParams.searchByName = ""
      this.getList()
    },
  }
};
</script>

<style scoped>
/*设置图书详情框最小宽度 */
::v-deep .infoDialog {

  min-width: 600px;
  /* width: 800px; */
}

.el-table .fixed-width .el-button--mini {
  padding: 6px;
}

</style>
